import React, { useState } from 'react';
import { useAppDispatch } from '../store';
import { addAction } from '../store/action/todo';

export default function Header() {
  const [task, setTask] = useState('');

  const dispatch = useAppDispatch();

  // * 1. 改造受控组件
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setTask(e.target.value);
  };

  const handleKeyDonw = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // * 2. 监听回车事件
    if (e.key === 'Enter') {
      console.log('123  ----->  ', 123);
      // * 5. dispatch触发action
      dispatch(addAction({ id: Date.now(), task, isDone: false }));
      setTask('');
    }
  };
  return (
    <header className="header">
      <h1>todos</h1>
      <input
        onChange={handleChange}
        onKeyDown={handleKeyDonw}
        value={task}
        className="new-todo"
        placeholder="需要做什么"
        autoFocus
      />
    </header>
  );
}
